import request from '@/utils/request'

// 聊天相关类型定义
export interface ChatUser {
    id: number
    username: string
    real_name?: string
    avatar?: string
    role: string
    online?: boolean
    last_seen?: string
    status?: string
}

export interface ChatMessage {
    id: number
    sender_id: number
    receiver_id?: number  // 后端可能不返回这个字段
    chat_id?: number      // 后端返回的chat_id
    content: string
    type: 'text' | 'image' | 'file' | 'system'  // 后端使用type而不是message_type
    message_type?: 'text' | 'image' | 'file'     // 保持兼容性
    sent_at: string       // 后端使用sent_at而不是created_at
    created_at?: string   // 保持兼容性
    read_at?: string      // 后端使用read_at而不是is_read
    is_read?: boolean     // 保持兼容性，根据read_at计算
    status?: string       // 消息状态：sent, delivered, read, failed
    sender?: ChatUser
}

export interface ChatConversation {
    id: number
    user1_id?: number     // 后端使用user1_id和user2_id
    user2_id?: number
    user_id?: number      // 保持兼容性
    other_user_id?: number // 保持兼容性
    last_message?: ChatMessage
    unread_count: number
    last_message_at?: string // 后端使用last_message_at
    updated_at: string
    other_user?: ChatUser // 保持兼容性
    user1?: ChatUser      // 后端返回的user1
    user2?: ChatUser      // 后端返回的user2
}

export interface SendMessageRequest {
    receiver_id: number
    content: string
    type?: 'text' | 'image' | 'file' | 'system'  // 后端使用type
    message_type?: 'text' | 'image' | 'file'     // 保持兼容性
}

export interface GetMessagesRequest {
    other_user_id: number
    page?: number
    size?: number      // 后端使用size而不是page_size
    page_size?: number // 保持兼容性
}

// API接口
export const getChatConversationsAPI = () => {
    return request.get('/chat/conversations')
}

export const getChatMessagesAPI = (params: GetMessagesRequest) => {
    // 适配后端参数格式
    const backendParams = {
        other_user_id: params.other_user_id,
        page: params.page || 1,
        size: params.size || params.page_size || 20
    }
    return request.get('/chat/messages', { params: backendParams })
}

export const sendChatMessageAPI = (data: SendMessageRequest) => {
    // 适配后端参数格式
    const backendData = {
        content: data.content,
        type: data.type || data.message_type || 'text',
        receiver_id: data.receiver_id
    }
    // 将receiver_id作为查询参数传递
    return request.post(`/chat/messages?receiver_id=${data.receiver_id}`, backendData)
}

export const markMessagesAsReadAPI = (other_user_id: number) => {
    return request.put(`/chat/messages/read/${other_user_id}`)
}

export const getOnlineUsersAPI = () => {
    return request.get('/chat/online-users')
}

export const searchUsersAPI = (keyword: string) => {
    return request.get('/chat/search-users', { params: { keyword } })
}

export const createConversationAPI = (other_user_id: number) => {
    return request.post('/chat/conversations', { other_user_id })
}

